import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.commons.io.IOUtils;
import tomcat.HttpRequest;
import tomcat.HttpResponse;
import tomcat.Router;
import tomcat.Servlet;


import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.Executor;

public class TomcatServer {
    private static final int port = 8081;

    public static void main(String... args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        // create a default executor
        server.setExecutor(null);

        // 扫描所有 Servlet，并把路由打印出来
        for (Map.Entry<String, Servlet> entry : Router.INSTANCE.getRouteMap().entrySet()) {
            System.out.printf("register url [%s,%s]\n", entry.getKey(), entry.getValue().getClass().getName());
            server.createContext(entry.getKey(), new DefaultHandler(entry.getKey(), entry.getValue()));
        }

        // 开启服务器
        server.start();
        System.out.printf("MyTomcatHttpServer running. 0.0.0.0:%d\n", port);
    }

    static class DefaultHandler implements HttpHandler {
        private String url;
        private Servlet servlet;

        DefaultHandler(String url, Servlet servlet) {
            this.url = url;
            this.servlet = servlet;
        }

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            HttpRequest request = new HttpRequest(url);
            // 获得查询字符串(get)
            request.setQueryString(httpExchange.getRequestURI().getQuery());
            // 获取post数据
            request.setContent(IOUtils.toString(httpExchange.getRequestBody(), "utf-8"));

            HttpResponse response = servlet.handle(request);
            httpExchange.sendResponseHeaders(response.getCode(), response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getContent().getBytes());
            os.close();
        }
    }
}
